/*
 * @Author: xuyijie
 * @Date: 2022-12-06 08:39:46
 * @LastEditors: xuyijie
 * @LastEditTime: 2023-01-29 10:32:19
 * @Description: 文件说明
 */
import useUtil from '@/composables/hd/useUtil'
import router from '@/router'
import { defineStore } from 'pinia'
import { RouteLocationRaw, RouteRecordNormalized, RouteRecordRaw } from 'vue-router'
const { open } = useUtil()
const key = ref(0)
export default defineStore('adminMenu', () => {
  const menuState = ref(true)
  //Vue 提示如果动态组件绑定的是一个ref 的响应式对象会造成不必要的性能问题，建议用 markRaw 或者 shallowRef 代替 ref 由于Vue3中动态组件绑定的是组件实力并不是组件名称，所以用shallowRef来解决
  const routes = shallowRef<RouteRecordNormalized[]>()
  routes.value = router
    .getRoutes()
    .filter((r) => r.children.length)
    .filter((r) => r.meta.menu)
    .sort((a, b) => {
      return (b.meta.menu?.order ?? 0) - (a.meta.menu?.order ?? 0)
    })

  const toggleMenu = () => {
    menuState.value = !menuState.value
  }
  const go = (route: RouteRecordRaw) => {
    if (route.meta?.menu?.blank) open(route, '_blank')
    else router.push(route)
  }

  const toggleClose = (route: RouteRecordNormalized) => {
    routes.value?.forEach((r) => {
      if (r.path === route.path) {
        r.meta.isClick = !r.meta.isClick
      }
    })
    key.value++
  }
  return { menuState, toggleMenu, routes, go, toggleClose, key }
})
